package com.feihong.yw189.bluetooth.utils.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.feihong.yw189.localdb.LoginInfoHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2017/2/15.
 */
//身份证读卡类，实现通道请求后台数据传输通道创建，照片解码等一系列操作
public class IDCardReadCtrl extends Thread {
    private static final String TAG = "IDCardReadCtrl";
    Context m_ctx = null;
    //////////////////////////////////////////
    private CardDeviceIO m_CardDeviceIO;
    ///////////////////////////
    private String m_strAllocApp;
    private String m_strToken;
    private String m_strBmpURL;
    private int m_nWaiteTime;
    private  Handler m_handler;
    ///////////////////////////////////////////////////
    public void StartRead(Context ctx, CardDeviceIO cardDevice, String strAllocApp, int nWaiteTime, Handler handler)
    {
        m_ctx = ctx;
        m_CardDeviceIO = cardDevice;
        m_strAllocApp = strAllocApp;
        m_nWaiteTime = nWaiteTime;
        m_handler = handler;
        start();
    }

    @Override
    public void run() {
        super.run();
        ReadIDCardAllInOne(m_ctx, m_CardDeviceIO, m_strAllocApp, m_nWaiteTime, m_handler);
    }
    /////////////////////////////////////////////////////////////////////////////////////////////////
    public static String GetSystemInfo(Context ctx)
    {
        String handSetInfo=
                "MobileType:" + android.os.Build.MODEL +
                        ",SDK:" + android.os.Build.VERSION.SDK +
                        ",SysVer:" + android.os.Build.VERSION.RELEASE+
                        ",SoftVer:"+getAppVersionName(ctx);
        return handSetInfo;
    }

    //获取当前版本号
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
            if (TextUtils.isEmpty(versionName)) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public  static String GetNetworkType(Context context)
    {
        String strNetworkType = null;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            strNetworkType = networkInfo.getTypeName();
            if (strNetworkType.equalsIgnoreCase("MOBILE")) {
                TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
                switch (telephonyManager.getNetworkType()) {
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                        strNetworkType =  "1xRTT"; // ~ 50-100 kbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                        strNetworkType = "CDMA";// ~ 14-64 kbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                        strNetworkType = "EDGE"; // ~ 50-100 kbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        strNetworkType = "EVDO_0"; // ~ 400-1000 kbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                        strNetworkType = "EVDO_A"; // ~ 600-1400 kbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                        strNetworkType = "GPRS";// ~ 100 kbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                        strNetworkType =  "HSDPA";// ~ 2-14 Mbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                        strNetworkType = "HSPA";// ~ 700-1700 kbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                        strNetworkType = "HSUPA";// ~ 1-23 Mbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                        strNetworkType = "UMTS"; // ~ 400-7000 kbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_EHRPD:
                        strNetworkType = "EHRPD"; // ~ 1-2 Mbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_EVDO_B:
                        strNetworkType = "EVDO_B";// ~ 5 Mbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_HSPAP:
                        strNetworkType =  "HSPAP";// ~ 10-20 Mbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_IDEN:
                        strNetworkType = "IDEN"; // ~25 kbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        strNetworkType = "LTE";// ~ 10+ Mbps
                        break;
                    case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                        strNetworkType = "UNKNOWN";
                        break;
                }
            }
        }
        else
            strNetworkType = "";
        return strNetworkType;
    }

    static IDCardBaseInfo ReadCardRemote(Context ctx, CardDeviceIO cardDeviceIO, AccelerateCache accelerateCache, String strIP, int nCardReaderPort, int nTransPort, boolean bUDP, String strAccelerate, int nWaiteTime)
    {
        int nRet = 1;
        IDCardReaderBase idCardReaderBase = new IDCardReaderBase(ctx);
        IDCardBaseInfo idCardBaseInfo = new IDCardBaseInfo();
        FrameTrans frameTrans = new FrameTrans();
        frameTrans.StartTrans(cardDeviceIO, accelerateCache, strIP, nTransPort, bUDP, idCardReaderBase.m_ErrHandler);
        {
            try{
                byte[] SW = new byte[3];
                byte[] iDCardData = new byte[4 + 256 + 1024];
                nRet = idCardReaderBase.ReadCardOneCard(strIP, nCardReaderPort, bUDP, iDCardData, SW, nWaiteTime);
                if (nRet == 0)
                {
                    idCardBaseInfo.m_data = iDCardData;
                    idCardBaseInfo.m_strErrorInfo = "OK";
                }
                idCardBaseInfo.m_SW = SW;
                idCardBaseInfo.m_nErrorCode = nRet;
            }catch (IOException e) {
                // TODO Auto-generated catch block
                idCardBaseInfo.m_strErrorInfo = e.getMessage();
                e.printStackTrace();
            }
            if (nRet == 0)
                cardDeviceIO.Beep();
        }
        {
            accelerateCache.Stop();
            frameTrans.StopTrans();
        }
        return idCardBaseInfo;
    }

    static void ReadIDCardAllInOne(Context ctx, CardDeviceIO cardDeviceIO, String strAllocApp, int nWaiteTime, Handler handler)
    {
        String strCientSN = "";
        String strClientVer = "";
        String strUser = "";
        String strPWD = "";
        ///////////////////////
        String strIP= null;
        boolean bUDP = true;
        int nCardReaderPort = 0;
        int nTransPort = 0;
        /*
        strIP= MainActivity.m_strServerAddress;
        bUDP = MainActivity.m_bUDP;
        nCardReaderPort = MainActivity.m_nCardReaderPort;
        nTransPort = MainActivity.m_nTransPort;
        */
        String strToken = null;
        String strAccelerate=null;
        String strBmpURL=null;
        //////////////////////
        String strResultInfo = null;
        {
            strCientSN = cardDeviceIO.GetDeviceSN();
            strClientVer = cardDeviceIO.GetDeviceVer();
        }
        if (strClientVer == null || strCientSN == null)
        {
            strResultInfo = "get version error!";
            strAllocApp = null;
        }
        if (strAllocApp != null)
        {
            Log.i(TAG, "ReadIDCardAllInOne: Alloc Channel!");
            String allocURL = strAllocApp;
            if (!allocURL.endsWith("/"))
                allocURL += "/";
            allocURL += "channel_alloc";
            String strNetworkType = GetNetworkType(ctx);
            String strSystemInfo = GetSystemInfo(ctx);
            String strDeviceType = cardDeviceIO.GetDeviceType();
            try{
                strCientSN = URLEncoder.encode(strCientSN, "utf-8");
                if (strClientVer != null)
                    strClientVer = URLEncoder.encode(strClientVer, "utf-8");
                strUser = URLEncoder.encode(strUser, "utf-8");
                strPWD = URLEncoder.encode(strPWD, "utf-8");
                ///////////////////////////////////////
                strNetworkType = URLEncoder.encode(strNetworkType, "utf-8");
                strSystemInfo = URLEncoder.encode(strSystemInfo, "utf-8");
                strDeviceType = URLEncoder.encode(strDeviceType, "utf-8");
            }
            catch(UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }

            String strParams = "ClientSN="+strCientSN
                    +"&ClientVer="+strClientVer
                    +"&User="+strUser
                    +"&Password="+strPWD
                    +"&OverTime="+0
                    +"&HostType=AndroidMobile"
                    +"&NetworkType="+strNetworkType
                    +"&SystemInfo="+strSystemInfo
                    +"&DeviceType="+strDeviceType;
            byte[] responseBuff = BmpDecrypt.RequestToUrl(allocURL + "?" + strParams, "GET", null);
            if (responseBuff != null)
            {
                String strJSON = new String(responseBuff);
                Log.i(TAG, "ReadIDCardAllInOne: " + strJSON);
                try {
                    JSONObject jsonObj = new JSONObject(strJSON);
                    boolean bRet = jsonObj.getBoolean("result");
                    if (bRet) {
                        strIP = jsonObj.getString("ip");
                        nCardReaderPort = jsonObj.getInt("ReaderPort");
                        nTransPort = jsonObj.getInt("TransPort");
                        strToken = jsonObj.getString("token");
                        strBmpURL = jsonObj.getString("bmpServer");
                        String strProtocol = jsonObj.getString("Protocol");
                        if (strProtocol.equals("TCP"))
                            bUDP = false;
                        strAccelerate = jsonObj.getString("Accelerate");
                    }
                    else
                    {
                        strResultInfo = "Alloc error";
                    }
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                    strResultInfo = "JSON error";
                }
            }
            else
            {
                strResultInfo = "connect Server error";
            }
        }
        IDCardBaseInfo idCardBaseInfo = null;
        String strWLTBase64 = null;
        String strErrorInfo = "NULL";
        if (strIP != null) {
            AccelerateCache accelerateCache;
            accelerateCache = new AccelerateCache(false, strAccelerate, 10000);
            accelerateCache.SetTransChannel(cardDeviceIO);
            accelerateCache.Start();
            idCardBaseInfo = ReadCardRemote(ctx, cardDeviceIO, accelerateCache, strIP, nCardReaderPort, nTransPort, bUDP, strAccelerate, nWaiteTime);
            if (idCardBaseInfo != null) {
                strResultInfo = idCardBaseInfo.GetResultText();
                strErrorInfo = idCardBaseInfo.GetErrorInfo();
                strWLTBase64 = idCardBaseInfo.GetWLTBase64();
            }
            accelerateCache.Stop();
        }
        cardDeviceIO.UninitDevice(false);
        if (handler != null) {
            Message msg1 = handler.obtainMessage(1, strResultInfo);
            msg1.sendToTarget();
        }
        if (strAllocApp != null)
        {
            Log.i(TAG, "ReadIDCardAllInOne: Free Channel!");
            if (strIP != null && strToken != null) {
                String allocURL = strAllocApp;
                if (!allocURL.endsWith("/"))
                    allocURL += "/";
                allocURL += "channel_free";
                String strParams = "";
                try {
                    strParams += "Token=" + URLEncoder.encode(strToken, "utf-8");
                    strParams += "&Result=" + URLEncoder.encode(strErrorInfo, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                BmpDecrypt.RequestToUrl(allocURL + "?" + strParams, "GET", null);
            }
        }
        if (strWLTBase64 != null) {
            Bitmap bitmap = null;
            if (strBmpURL != null)
                bitmap = BmpDecrypt.BmpDecryptRemote(strBmpURL, strCientSN, strToken, strWLTBase64);
            ///////////////////////////////////
            if (handler != null) {
                Message msg = handler.obtainMessage(0, bitmap);
                msg.sendToTarget();
            }
        }
    }
}
